package controller

import (
	"github.com/gin-gonic/gin"
	"shop-bean/dto"
	"shop-bean/model"
	"shop-bean/request"
	"shop-common/library/serializer"
	"shop-common/library/variables"
	"shop-common/utils/contextArgs"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
	"shop-common/utils/regular"
	"shop-common/utils/uploader"
	"shop-service/business"
	"strconv"
	"strings"
)

type PictureController struct {
}

func (c *PictureController) Page(ctx *gin.Context) {
	form := pagehelper.SearchPageRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	pid, err := contextArgs.GetUriIntQuery(ctx, "pid")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	paginator := pagehelper.New().SetOffset(form).
		//Push(&queryWrapper.WherePair{Query: "att_type in ?", Args: []interface{}{strings.Split("jpg,jpeg,gif,png,bmp,PNG,JPG,webp,WEBP", ",")}}).
		IsPush(pid > 0, queryWrapper.Eq("pid", pid)).
		SetFilter([]string{"att_id"}).Paginator()

	var count int64
	var page []*model.Attachment
	tx := queryWrapper.ReuseSelect(variables.GormDB().Model(&model.Attachment{}), paginator.Params.SelectFields)
	err = queryWrapper.ReuseWherePair(tx, paginator.Params.WherePair).Count(&count).Error
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	if count == 0 {
		serializer.SuccessData(ctx, "", paginator.Record)
		return
	}

	err = queryWrapper.ReuseWherePair(variables.GormDB().Model(&model.Attachment{}), paginator.Params.WherePair).
		Scopes(pagehelper.Paginate(paginator.Params.Current, paginator.Params.Size)).Order("att_id desc").Find(&page).Error

	var files []*dto.AttachmentDTO
	for _, item := range page {
		files = append(files, &dto.AttachmentDTO{
			AttId:       item.AttId,
			RealName:    item.RealName,
			Name:        item.Name,
			Url:         strings.Join([]string{uploader.GetHostStatic(item.ImageType), item.AttDir, item.Name}, ""),
			AttDir:      item.AttDir,
			AttSize:     item.AttSize,
			AttType:     item.AttType,
			ContentType: item.ContentType,
			Pid:         item.Pid,
			ImageType:   item.ImageType,
		})
	}

	paginator.Count(count).Record.List = files

	serializer.SuccessData(ctx, "", paginator.Record)
}

func (c *PictureController) Refactor(ctx *gin.Context) {
	form := request.AttachmentRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	info := &model.Attachment{}
	if err := variables.GormDB().First(&info, form.AttId).Error; err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	if info == nil {
		serializer.Fail(ctx, "未查询到数据")
		return
	}

	if form.Name == info.Name {
		serializer.Success(ctx, "")
	}

	err := business.ServiceImpl().PictureService.Move(&form, info)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	serializer.Success(ctx, "")
}

func (c *PictureController) UpdatePid(ctx *gin.Context) {
	form := request.AttachmentMoveRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	err := variables.GormDB().Model(&model.Attachment{}).Where("att_id in ?", strings.Split(form.Images, ",")).Update("pid", form.Pid).Error
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	serializer.Success(ctx, "")
}

func (c *PictureController) Delete(ctx *gin.Context) {
	form := request.AttachmentBatchRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	var rows []*model.Attachment
	err := variables.GormDB().Model(&model.Attachment{}).Where("att_id in ?", form.AttIds).Find(&rows).Error
	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}

	err = business.ServiceImpl().PictureService.DeleteBatch(rows)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}

	serializer.Success(ctx, "")
}

func (c *PictureController) AttIds(ctx *gin.Context) {
	idsStr, err := contextArgs.GetUriQuery(ctx, "ids")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	var ids []uint
	for _, i := range strings.Split(idsStr, ",") {
		id, err := strconv.Atoi(i)
		if err != nil {
			break
		}
		ids = append(ids, uint(id))
	}

	if len(ids) > 0 {
		list, err := business.ServiceImpl().PictureService.FindAttIds(ids)
		if err != nil {
			serializer.Fail(ctx, serializer.PublicQueryErr)
			return
		}
		serializer.SuccessData(ctx, "", list)
	} else {
		serializer.Success(ctx, "")
	}

}

// @Tags 附件
// @Summary 普通图片上传
// @Security ApiKeyAuth
// @function: Image
// @accept multipart/form-data
// @Produce  application/json
// @Param file formData file true "普通上传"
// @Success 200 {string} string "{"success":true,"data":{},"msg":""}"
// @Router /attachment/image [post]
func (c *PictureController) Image(ctx *gin.Context) {
	userId, _ := contextArgs.GetUserInternalId(ctx)
	pid, err := strconv.Atoi(ctx.Request.FormValue("pid"))
	if err != nil {
		serializer.Fail(ctx, "分类id不正确")
		return
	}

	file, header, err := ctx.Request.FormFile("file")
	defer file.Close()
	if err != nil {
		serializer.Fail(ctx, "获取文件失败")
		return
	}
	validFile, err := uploader.ValidUploadRequest(file, header)
	if err != nil {
		serializer.Fail(ctx, "获取文件失败")
		return
	}

	if !regular.IsImageContentType(validFile.FileType) {
		serializer.Fail(ctx, "上传文件的类型只能是: jpg|jpeg|png|gif|webp")
		return
	}

	upload, err := business.ServiceImpl().PictureService.Put(userId, uint(pid), validFile)
	if err != nil {
		serializer.Fail(ctx, "上传失败")
		return
	}

	serializer.SuccessData(ctx, "", upload)
}
